import json
import websocket
import requests
import re

class Feed(object):
    def __init__(self):
        self.url = 'ws://localhost:6700/event'
        self.api = 'http://localhost:5700'# 这里输入websocket的url
        self.ws = None

    def on_open(self, ws):
        """
        Callback object which is called at opening websocket.
        1 argument:
        @ ws: the WebSocketApp object
        """
        print('A new WebSocketApp is opened!')

    def on_data(self, ws, string, type, continue_flag):
        """
        4 argument.
        The 1st argument is this class object.
        The 2nd argument is utf-8 string which we get from the server.
        The 3rd argument is data type. ABNF.OPCODE_TEXT or ABNF.OPCODE_BINARY will be came.
        The 4th argument is continue flag. If 0, the data continue
        """

    def on_message(self, ws, message):
        """
        Callback object which is called when received data.
        2 arguments:
        @ ws: the WebSocketApp object
        @ message: utf-8 data received from the server
        """
        # 对收到的message进行解析
        print(message)
        self.messageHandler(json.loads(message))


    def on_error(self, ws, error):
        """
        Callback object which is called when got an error.
        2 arguments:
        @ ws: the WebSocketApp object
        @ error: exception object
        """
        print(error)

    def on_close(self, ws, close_status_code, close_msg):
        """
        Callback object which is called when the connection is closed.
        2 arguments:
        @ ws: the WebSocketApp object
        @ close_status_code
        @ close_msg
        """
        print('The connection is closed!')

    def start(self):
        self.ws = websocket.WebSocketApp(
            self.url,
            on_open=self.on_open,
            on_message=self.on_message,
            on_data=self.on_data,
            on_error=self.on_error,
            on_close=self.on_close,
        )
        self.ws.run_forever()

    def messageHandler(self, message):
        if message["message_type"] == "private":
            self.privateHandler(message)
        elif message["message_type"] == "group":
            self.groupHandler(message)

    def privateHandler(self, message):
        raw_message = message["raw_message"]
        user_id = message["user_id"]
        reply = self.resolveMessage(raw_message)
        if reply != "":
            self.sendPrivateMassage(user_id, None, reply, False)

    def groupHandler(self, message):
        raw_message = message["raw_message"]
        group_id = message["group_id"]
        reply = self.resolveMessage(raw_message)
        if reply != "":
            self.sendGroupMassage(group_id, reply, False)

    def sendPrivateMassage(self,user_id, group_id, message, auto_escape):
        url = self.api+"/send_private_msg"
        data = {}
        data["user_id"] = user_id
        data["group_id"] = group_id
        data["message"] = message
        data["auto_escape"] = auto_escape
        requests.post(url, data)

    def sendGroupMassage(self, group_id, message, auto_escape):
        url = self.api+"/send_group_msg"
        data = {}
        data["group_id"] = group_id
        data["message"] = message
        data["auto_escape"] = auto_escape
        requests.post(url, data)

    def resolveMessage(self, message):
        if message.startswith("/攻略 "):
            keyword = "ff14" + message[3:] + "攻略"
            print(keyword)
            result = requests.get(
                "https://api.bilibili.com/x/web-interface/search/type?__refresh__=true&_extra=&context=&page=1&page_size=42&order=click&from_source=&from_spmid=333.337&platform=pc&highlight=1&single_column=0&keyword=" + keyword + "&category_id=&search_type=video&dynamic_offset=0&preload=true&com2co=true").json()
            videos = result["data"]["result"]
            titles = []
            urls = []
            for v in videos[0:3]:
                pattern = re.compile(r'<[^>]+>', re.S)
                text = pattern.sub('', v["title"])
                titles.append(text)
                urls.append(v["arcurl"])

            reply = "找到了以下攻略:\n"
            for (t, u) in zip(titles, urls):
                reply = reply + t + "\n" + u + "\n"
            return reply
        return ""


if __name__ == "__main__":
    feed = Feed()
    feed.start()